package cn.singlewindow.ha.util.collector.collecter.service.impl;

import cn.singlewindow.ha.util.collector.collecter.constant.DataTableConstant;
import cn.singlewindow.ha.util.collector.collecter.domain.CompanyNature;
import cn.singlewindow.ha.util.collector.collecter.domain.CountryArea;
import cn.singlewindow.ha.util.collector.collecter.domain.GoodsCategory;
import cn.singlewindow.ha.util.collector.collecter.domain.TradeMode;
import cn.singlewindow.ha.util.collector.collecter.mapper.CompanyNatureMapper;
import cn.singlewindow.ha.util.collector.collecter.mapper.CountryAreaMapper;
import cn.singlewindow.ha.util.collector.collecter.mapper.GoodsCategoryMapper;
import cn.singlewindow.ha.util.collector.collecter.mapper.TradeModeMapper;
import cn.singlewindow.ha.util.collector.collecter.service.IParserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class ParserService implements IParserService {

    private final static Log logger = LogFactory.getLog(ParserService.class);

    @Autowired
    private GoodsCategoryMapper goodsCategoryMapper;
    @Autowired
    private CompanyNatureMapper companyNatureMapper;
    @Autowired
    private CountryAreaMapper countryAreaMapper;
    @Autowired
    private TradeModeMapper tradeModeMapper;

    /**
     * 1 获取文件名，有：匹配后缀，无，不处理
     * 2 后缀html,做html处理table，xlsx做excel处理
     * 3 html获取
     * @param message
     */
    @Override
    public void messageParser(Message message) {
    }

    @Override
    public void messageParser(byte[] bytes) {
    }

    @Override
    public boolean htmlParser(String payload) {
        try {

            Document document = Jsoup.parse(payload);
            // 获取标题
            Elements body = document.getElementsByTag("body");
            String bodyHtml=body.get(0).html();
            String title = bodyHtml.substring(0,bodyHtml.indexOf("<br>")).trim();

            String dataType = DataTableConstant.OTHER_TYPE;
            if(title.contains(DataTableConstant.GOODS_CATEGORY)) {
                dataType = DataTableConstant.GOODS_CATEGORY;
            }else if(title.contains(DataTableConstant.COMPANY_NATURE)){
                dataType = DataTableConstant.COMPANY_NATURE;
            }else if(title.contains(DataTableConstant.COUNTRY_AREA)){
                dataType = DataTableConstant.COUNTRY_AREA;
            }else if(title.contains(DataTableConstant.TRADE_MODE)){
                dataType = DataTableConstant.TRADE_MODE;
            }
            logger.info(String.format("开始处理类型[%s]，原文件名：[%s]",dataType,title));
            System.out.println(String.format("开始处理类型[%s]，原文件名：[%s]",dataType,title));
            if(DataTableConstant.OTHER_TYPE.equals(dataType)){
                return false;
            }

            // 获取表格
            Elements tableRows = document.getElementsByTag("table").get(0).select("tr");
            // 配置固定数据
            String proviceName = "河南省";
            String ieType ="";
            String yearValue = "";
            int monthValue = 0;
            String yearMonthValue = "";
            yearValue = title.substring(0,title.indexOf("年"));
            monthValue = title.substring(title.indexOf("年")+1,title.indexOf("月")).contains("至")?Integer.valueOf(title.substring(title.indexOf("至")+1,title.indexOf("月"))):Integer.valueOf(title.substring(title.indexOf("年")+1,title.indexOf("月")));
            yearMonthValue = yearValue+String.format("%02d",monthValue);
            proviceName = title.contains("省")?title.substring(title.indexOf("月")+1,title.indexOf("省")+1):"";
            if(!title.contains("进出口")){
                if(title.indexOf("进口")!=-1){
                    ieType = "I";
                } else if(title.indexOf("出口")!=-1){
                    ieType = "E";
                }
            }

            if(tableRows.size()==1){
                System.out.println("没有数据");
                logger.error("本次处理表格中没有数据");
            } else {
                if(dataType.equals(DataTableConstant.GOODS_CATEGORY)){
                    String text = "";
                    String first_class = "";
                    String second_class = "";
                    String third_class = "";
                    List<String> rowValueList = null;
                    boolean is2018AndBefore = false;
                    for(int i=0;i<tableRows.size();i++){
                        Elements tds = tableRows.get(i).select("td");
                        boolean hasrowspan = false;
                        boolean hascolspan = false;
                        rowValueList = new ArrayList<>();
                        for(int j=0;j<tds.size();j++){
                            String rowspan = tds.get(j).attr("rowspan");
                            String colspan = tds.get(j).attr("colspan");
                            text = tds.get(j).text();

                            if(text.contains("月")&&(text.contains("至"))){
                                is2018AndBefore = true;
                            }
                            if (StringUtils.hasLength(rowspan)) {
                                hasrowspan = true;
                                continue;
                            }
                            if (StringUtils.hasLength(colspan)) {
                                hascolspan = true;
                                continue;
                            }

                            if(j==0){
                                third_class = text.replace("　", "");
                                if (text.startsWith(DataTableConstant.FOURTH_CLASS_FLAG)) {
                                } else if (text.startsWith(DataTableConstant.THIRD_CLASS_FLAG)) {
                                } else if (text.startsWith(DataTableConstant.SECOND_CLASS_FLAG)) {
                                    second_class = text.replace("　", "");
                                } else {
                                    second_class = text.replace("　", "");
                                    first_class = text.replace("　", "");
                                }
                            } else {
                                text = text.replace("　","").replace(",","");
                                if ("--".equalsIgnoreCase(text)||".".equalsIgnoreCase(text)||".　".equalsIgnoreCase(text)||"-".equalsIgnoreCase(text)) {
                                    text = "";
                                }
                                if(text.contains("人民币")){
                                    hasrowspan = true;
                                    break;
                                }
                            }
                            rowValueList.add(j,text);
                        }
                        if(hasrowspan){
                            continue;
                        }
                        if(hascolspan){
                            continue;
                        }
                        try{

                            GoodsCategory object = null;
                            object = new GoodsCategory();
                            object.setGuid(UUID.randomUUID().toString());
                            object.setSysDate(new Date());
                            object.setProvinceName(proviceName);
                            object.setYearMonthValue(yearMonthValue);
                            object.setIeType(ieType);
                            object.setFirstClass(first_class);
                            object.setSecondClass(second_class);
                            object.setThirdClass(third_class);
                            if (StringUtils.hasLength(rowValueList.get(1))) {
                                object.setUnitName(rowValueList.get(1));
                            }
                            if (is2018AndBefore){
                                if (StringUtils.hasLength(rowValueList.get(6))) {
                                    object.setQty(new BigDecimal(rowValueList.get(6)));
                                }
                                if (StringUtils.hasLength(rowValueList.get(7))) {
                                    object.setQtyPercent(new BigDecimal(rowValueList.get(7)));
                                }
                                if (StringUtils.hasLength(rowValueList.get(8))) {
                                    object.setTotalValue(new BigDecimal(rowValueList.get(8)));
                                }
                                if (StringUtils.hasLength(rowValueList.get(9))) {
                                    object.setTotalValuePercent(new BigDecimal(rowValueList.get(9)));
                                }
                            } else {
                                if (StringUtils.hasLength(rowValueList.get(2))) {
                                    object.setQty(new BigDecimal(rowValueList.get(2)));
                                }
                                if (StringUtils.hasLength(rowValueList.get(3))) {
                                    object.setQtyPercent(new BigDecimal(rowValueList.get(3)));
                                }
                                if (StringUtils.hasLength(rowValueList.get(4))) {
                                    object.setTotalValue(new BigDecimal(rowValueList.get(4)));
                                }
                                if (StringUtils.hasLength(rowValueList.get(5))) {
                                    object.setTotalValuePercent(new BigDecimal(rowValueList.get(5)));
                                }
                            }
                            LambdaQueryWrapper<GoodsCategory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                            lambdaQueryWrapper.eq(GoodsCategory::getYearMonthValue,object.getYearMonthValue());
                            lambdaQueryWrapper.eq(GoodsCategory::getProvinceName,object.getProvinceName());
                            lambdaQueryWrapper.eq(GoodsCategory::getFirstClass,object.getFirstClass());
                            lambdaQueryWrapper.eq(GoodsCategory::getSecondClass,object.getSecondClass());
                            lambdaQueryWrapper.eq(GoodsCategory::getThirdClass,object.getThirdClass());
                            lambdaQueryWrapper.eq(GoodsCategory::getIeType,object.getIeType());

                            GoodsCategory dbObject = goodsCategoryMapper.selectOne(lambdaQueryWrapper);
                            if(null != dbObject){
                                goodsCategoryMapper.delete(lambdaQueryWrapper);
                            }
                            goodsCategoryMapper.insert(object);
                        } catch (Exception e){
                            e.printStackTrace();
                            logger.error(String.format("处理错误，文件：[%s],行：[%s],值：[%s]",title,i,rowValueList));
                            continue;
                        }
                    }
                } else {
                    String text = "";
                    String first_class = "";
                    String second_class = "";
                    List<String> rowValueList = null;
                    List<Integer> dataColumnIndexsI = new ArrayList<>();
                    List<Integer> dataColumnIndexsE = new ArrayList<>();
                    int skipRowNum = 0;
                    for(int i=0;i<tableRows.size();i++) {
                        Elements tds = tableRows.get(i).select("td");
                        boolean hasrowspan = false;
                        boolean hascolspan = false;
                        rowValueList = new ArrayList<>();
                        int beginIndex = 0;
                        for (int j = 0; j < tds.size(); j++) {
                            String rowspan = tds.get(j).attr("rowspan");
                            String colspan = tds.get(j).attr("colspan");
                            text = tds.get(j).text();
                            if(i == 0){
                                if(text.contains("进出口")) {
                                } else if(text.contains("出口")){
                                    dataColumnIndexsE.add(beginIndex);
                                    dataColumnIndexsE.add(beginIndex+1);
                                } else if(text.contains("进口")){
                                    dataColumnIndexsI.add(beginIndex);
                                    dataColumnIndexsI.add(beginIndex+1);
                                }else {
                                    beginIndex +=1;
                                }
                                if(StringUtils.hasLength(colspan)){
                                    beginIndex += Integer.valueOf(colspan);
                                }
                                if (j == 0 && StringUtils.hasLength(rowspan)) {
                                    skipRowNum = Integer.valueOf(rowspan);
                                }
                            } else {
                                if (StringUtils.hasLength(rowspan)) {
                                    hasrowspan = true;
                                    i += Integer.valueOf(rowspan) - 1;
                                    break;
                                }
                                if (StringUtils.hasLength(colspan)) {
                                    hascolspan = true;
                                    continue;
                                }
                                if (j == 0) {
                                    second_class = text.replace("　", "");
                                    if (text.startsWith(DataTableConstant.FOURTH_CLASS_FLAG)) {
                                    } else if (text.startsWith(DataTableConstant.THIRD_CLASS_FLAG)) {
                                    } else if (text.startsWith(DataTableConstant.SECOND_CLASS_FLAG)) {
                                    } else if (text.startsWith(DataTableConstant.FIRST_CLASS_FLAG)) {
                                    } else {
                                        first_class = text.replace("　", "");
                                    }
                                } else {
                                    text = text.replace("　", "").replace(",", "");
                                    if ("--".equalsIgnoreCase(text)||".".equalsIgnoreCase(text)||".　".equalsIgnoreCase(text)||"-".equalsIgnoreCase(text)) {
                                        text = "";
                                    }
                                    if(text.contains("人民币")){
                                        hasrowspan = true;
                                        break;
                                    }
                                }
                                rowValueList.add(j, text);
                            }
                        }
                        if(i<skipRowNum){
                            continue;
                        }
                        if (hasrowspan) {
                            continue;
                        }
                        if (hascolspan) {
                            continue;
                        }
                        try {
                            if(dataType.equals(DataTableConstant.COMPANY_NATURE)) {
                                CompanyNature object = null;
                                object = new CompanyNature();
                                object.setProvinceName(proviceName);
                                object.setYearMonthValue(yearMonthValue);
                                object.setFirstClass(first_class);
                                object.setSecondClass(second_class);

                                CompanyNature objectI = new CompanyNature();
                                CompanyNature objectE = new CompanyNature();
                                BeanUtils.copyProperties(object,objectI);
                                BeanUtils.copyProperties(object,objectE);

                                objectI.setGuid(UUID.randomUUID().toString());
                                objectE.setGuid(UUID.randomUUID().toString());
                                objectI.setSysDate(new Date());
                                objectE.setSysDate(new Date());
                                objectI.setIeType("I");
                                objectE.setIeType("E");

                                if(rowValueList.isEmpty()){
                                    continue;
                                }
                                if(StringUtils.hasLength(rowValueList.get(dataColumnIndexsE.get(0)))){
                                    objectE.setTotalValue(new BigDecimal(rowValueList.get(dataColumnIndexsE.get(0))));
                                }
                                if(StringUtils.hasLength(rowValueList.get(dataColumnIndexsE.get(1)))){
                                    objectE.setTotalValuePercent(new BigDecimal(rowValueList.get(dataColumnIndexsE.get(1))));
                                }
                                if(StringUtils.hasLength(rowValueList.get(dataColumnIndexsI.get(0)))){
                                    objectI.setTotalValue(new BigDecimal(rowValueList.get(dataColumnIndexsI.get(0))));
                                }
                                if(StringUtils.hasLength(rowValueList.get(dataColumnIndexsI.get(1)))){
                                    objectI.setTotalValuePercent(new BigDecimal(rowValueList.get(dataColumnIndexsI.get(1))));
                                }
                                LambdaQueryWrapper<CompanyNature> lambdaQueryWrapperI = new LambdaQueryWrapper<>();
                                lambdaQueryWrapperI.eq(CompanyNature::getYearMonthValue,objectI.getYearMonthValue());
                                lambdaQueryWrapperI.eq(CompanyNature::getProvinceName,objectI.getProvinceName());
                                lambdaQueryWrapperI.eq(CompanyNature::getFirstClass,objectI.getFirstClass());
                                lambdaQueryWrapperI.eq(CompanyNature::getSecondClass,objectI.getSecondClass());
                                lambdaQueryWrapperI.eq(CompanyNature::getIeType,objectI.getIeType());

                                CompanyNature dbObjectI = companyNatureMapper.selectOne(lambdaQueryWrapperI);
                                if(null != dbObjectI){
                                    companyNatureMapper.delete(lambdaQueryWrapperI);
                                }
                                companyNatureMapper.insert(objectI);

                                LambdaQueryWrapper<CompanyNature> lambdaQueryWrapperE = new LambdaQueryWrapper<>();
                                lambdaQueryWrapperE.eq(CompanyNature::getYearMonthValue,objectE.getYearMonthValue());
                                lambdaQueryWrapperE.eq(CompanyNature::getProvinceName,objectE.getProvinceName());
                                lambdaQueryWrapperE.eq(CompanyNature::getFirstClass,objectE.getFirstClass());
                                lambdaQueryWrapperE.eq(CompanyNature::getSecondClass,objectE.getSecondClass());
                                lambdaQueryWrapperE.eq(CompanyNature::getIeType,objectE.getIeType());

                                CompanyNature dbObjectE = companyNatureMapper.selectOne(lambdaQueryWrapperE);
                                if(null != dbObjectE){
                                    companyNatureMapper.delete(lambdaQueryWrapperE);
                                }
                                companyNatureMapper.insert(objectE);
                            } else if(dataType.equals(DataTableConstant.COUNTRY_AREA)) {
                                CountryArea object = null;
                                object = new CountryArea();
                                object.setProvinceName(proviceName);
                                object.setYearMonthValue(yearMonthValue);
                                object.setFirstClass(first_class);
                                object.setSecondClass(second_class);

                                CountryArea objectI = new CountryArea();
                                CountryArea objectE = new CountryArea();
                                BeanUtils.copyProperties(object,objectI);
                                BeanUtils.copyProperties(object,objectE);

                                objectI.setGuid(UUID.randomUUID().toString());
                                objectE.setGuid(UUID.randomUUID().toString());
                                objectI.setSysDate(new Date());
                                objectE.setSysDate(new Date());
                                objectI.setIeType("I");
                                objectE.setIeType("E");

                                if(rowValueList.isEmpty()){
                                    continue;
                                }
                                if(StringUtils.hasLength(rowValueList.get(dataColumnIndexsE.get(0)))){
                                    objectE.setTotalValue(new BigDecimal(rowValueList.get(dataColumnIndexsE.get(0))));
                                }
                                if(StringUtils.hasLength(rowValueList.get(dataColumnIndexsE.get(1)))){
                                    objectE.setTotalValuePercent(new BigDecimal(rowValueList.get(dataColumnIndexsE.get(1))));
                                }
                                if(StringUtils.hasLength(rowValueList.get(dataColumnIndexsI.get(0)))){
                                    objectI.setTotalValue(new BigDecimal(rowValueList.get(dataColumnIndexsI.get(0))));
                                }
                                if(StringUtils.hasLength(rowValueList.get(dataColumnIndexsI.get(1)))){
                                    objectI.setTotalValuePercent(new BigDecimal(rowValueList.get(dataColumnIndexsI.get(1))));
                                }

                                LambdaQueryWrapper<CountryArea> lambdaQueryWrapperI = new LambdaQueryWrapper<>();
                                lambdaQueryWrapperI.eq(CountryArea::getYearMonthValue,objectI.getYearMonthValue());
                                lambdaQueryWrapperI.eq(CountryArea::getProvinceName,objectI.getProvinceName());
                                lambdaQueryWrapperI.eq(CountryArea::getFirstClass,objectI.getFirstClass());
                                lambdaQueryWrapperI.eq(CountryArea::getSecondClass,objectI.getSecondClass());
                                lambdaQueryWrapperI.eq(CountryArea::getIeType,objectI.getIeType());

                                CountryArea dbObjectI = countryAreaMapper.selectOne(lambdaQueryWrapperI);
                                if(null != dbObjectI){
                                    countryAreaMapper.delete(lambdaQueryWrapperI);
                                }
                                countryAreaMapper.insert(objectI);

                                LambdaQueryWrapper<CountryArea> lambdaQueryWrapperE = new LambdaQueryWrapper<>();
                                lambdaQueryWrapperE.eq(CountryArea::getYearMonthValue,objectE.getYearMonthValue());
                                lambdaQueryWrapperE.eq(CountryArea::getProvinceName,objectE.getProvinceName());
                                lambdaQueryWrapperE.eq(CountryArea::getFirstClass,objectE.getFirstClass());
                                lambdaQueryWrapperE.eq(CountryArea::getSecondClass,objectE.getSecondClass());
                                lambdaQueryWrapperE.eq(CountryArea::getIeType,objectE.getIeType());

                                CountryArea dbObjectE = countryAreaMapper.selectOne(lambdaQueryWrapperE);
                                if(null != dbObjectE){
                                    countryAreaMapper.delete(lambdaQueryWrapperE);
                                }
                                countryAreaMapper.insert(objectE);
                            } else if(dataType.equals(DataTableConstant.TRADE_MODE)) {
                                TradeMode object = null;
                                object = new TradeMode();
                                object.setProvinceName(proviceName);
                                object.setYearMonthValue(yearMonthValue);
                                object.setFirstClass(first_class);
                                object.setSecondClass(second_class);

                                TradeMode objectI = new TradeMode();
                                TradeMode objectE = new TradeMode();
                                BeanUtils.copyProperties(object,objectI);
                                BeanUtils.copyProperties(object,objectE);

                                objectI.setGuid(UUID.randomUUID().toString());
                                objectE.setGuid(UUID.randomUUID().toString());
                                objectI.setSysDate(new Date());
                                objectE.setSysDate(new Date());
                                objectI.setIeType("I");
                                objectE.setIeType("E");

                                if(rowValueList.isEmpty()){
                                    continue;
                                }
                                if(StringUtils.hasLength(rowValueList.get(dataColumnIndexsE.get(0)))){
                                    objectE.setTotalValue(new BigDecimal(rowValueList.get(dataColumnIndexsE.get(0))));
                                }
                                if(StringUtils.hasLength(rowValueList.get(dataColumnIndexsE.get(1)))){
                                    objectE.setTotalValuePercent(new BigDecimal(rowValueList.get(dataColumnIndexsE.get(1))));
                                }
                                if(StringUtils.hasLength(rowValueList.get(dataColumnIndexsI.get(0)))){
                                    objectI.setTotalValue(new BigDecimal(rowValueList.get(dataColumnIndexsI.get(0))));
                                }
                                if(StringUtils.hasLength(rowValueList.get(dataColumnIndexsI.get(1)))){
                                    objectI.setTotalValuePercent(new BigDecimal(rowValueList.get(dataColumnIndexsI.get(1))));
                                }

                                LambdaQueryWrapper<TradeMode> lambdaQueryWrapperI = new LambdaQueryWrapper<>();
                                lambdaQueryWrapperI.eq(TradeMode::getYearMonthValue,objectI.getYearMonthValue());
                                lambdaQueryWrapperI.eq(TradeMode::getProvinceName,objectI.getProvinceName());
                                lambdaQueryWrapperI.eq(TradeMode::getFirstClass,objectI.getFirstClass());
                                lambdaQueryWrapperI.eq(TradeMode::getSecondClass,objectI.getSecondClass());
                                lambdaQueryWrapperI.eq(TradeMode::getIeType,objectI.getIeType());

                                TradeMode dbObjectI = tradeModeMapper.selectOne(lambdaQueryWrapperI);
                                if(null != dbObjectI){
                                    tradeModeMapper.delete(lambdaQueryWrapperI);
                                }
                                tradeModeMapper.insert(objectI);

                                LambdaQueryWrapper<TradeMode> lambdaQueryWrapperE = new LambdaQueryWrapper<>();
                                lambdaQueryWrapperE.eq(TradeMode::getYearMonthValue,objectE.getYearMonthValue());
                                lambdaQueryWrapperE.eq(TradeMode::getProvinceName,objectE.getProvinceName());
                                lambdaQueryWrapperE.eq(TradeMode::getFirstClass,objectE.getFirstClass());
                                lambdaQueryWrapperE.eq(TradeMode::getSecondClass,objectE.getSecondClass());
                                lambdaQueryWrapperE.eq(TradeMode::getIeType,objectE.getIeType());

                                TradeMode dbObjectE = tradeModeMapper.selectOne(lambdaQueryWrapperE);
                                if(null != dbObjectE){
                                    tradeModeMapper.delete(lambdaQueryWrapperE);
                                }
                                tradeModeMapper.insert(objectE);
                            }
                        } catch (Exception e){
                            e.printStackTrace();
                            logger.error(String.format("处理错误，文件：[%s],行：[%s],值：[%s]",title,i,rowValueList));
                            continue;
                        }
                    }
                }
            }
            return true;
        } catch (Exception e){
            logger.error(e);
            return false;
        }
    }

}
